package cn.yitun.chat.yitunserverfilecore.controller;

import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yituncommonutil.YitunStringUtil;
import cn.yitun.chat.yitunservercommonlib.basebean.web.JwtUserDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.po.common.ImageData;
import cn.yitun.chat.yitunserverfilecore.component.DownloadFileHandler;
import cn.yitun.chat.yitunserverfilecore.service.FileServerConfigService;
import cn.yitun.chat.yitunserverfilecore.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片上传下载接口
 * @author yitun
 * @date 2017-11-25 09:31:17
 *
 */
@Controller
@RequestMapping("/picture/image")
public class ImageUploadController {

	@Autowired
	ImageService imageService;
	@Resource
	FileServerConfigService fileServerConfigService;
	DownloadFileHandler dfh = new DownloadFileHandler();
	
	@CrossOrigin
	@ResponseBody
	@PostMapping("/upload")
	public Object userUpload(JwtUserDto jwtUserDto, HttpServletRequest request, HttpServletResponse response) {
		ResultMessage rm = new ResultMessage();
		Long userId = jwtUserDto.getUserId();
//		Long userId = YitunStringUtil.isNotEmpty(request.getParameter("userId"))
//				? null : Long.parseLong(request.getParameter("userId")) ;
		List<ImageData> list = imageService.uploadByIO(request, userId);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		if (null != list && !list.isEmpty()) {
			ImageData data = list.get(0);
			String name = data.getName();
			String saveName = data.getSaveName();
			String nodePath = data.getNodePath();

			dataMap.put("id", data.getId());
			dataMap.put("name", name);
			dataMap.put("size", data.getSize());
			dataMap.put("url", fileServerConfigService.getFileUrl(nodePath + saveName));
		}
		rm.bodyPut("data", dataMap);
		return rm;
	}

	@RequestMapping("/download")
	public void userDownload(Long id, HttpServletRequest request, HttpServletResponse response) {
		if (id != null) {
			ImageData fileData = imageService.getImageData(id);
			if (null != fileData) {
				dfh.downloadByIO(request, response, fileData);
			}
		}
	}
}
